package com.ws.wuse.http;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.ws.base.rxvolley.client.HttpCallback;
import com.ws.base.util.LogUtil;
import com.ws.wuse.app.Constant;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;

/**
 * User: zhanghang
 * Date: 2016-03-24
 * Time: 10:26
 * FIXME
 */
public abstract class BaseRequestListener<M> extends HttpCallback {

    @Override
    public void onPreHttp() {
        super.onPreHttp();
        onStart();
    }

    @Override
    public void onSuccess(String t) {
        super.onSuccess(t);
        LogUtil.e(Constant.TAG, "onSuccess result = " + t);
        try {
            JSONObject jsonObject = new JSONObject(t);
            int stat = jsonObject.optInt("stat");
            if (stat == 0) {
                String content = jsonObject.getString("content");
                LogUtil.e(Constant.TAG, "onSuccess content = " + content);
                if (!TextUtils.isEmpty(content)) {
                    Class<M> entityClass = (Class<M>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
                    M result = new Gson().fromJson(content, entityClass);
                    LogUtil.e(Constant.TAG, "onSuccess result = " + result.toString());
                    onSuccess(result);
                }
            } else if (stat == 20) {//重复登录
                LogUtil.e(Constant.TAG, "stat =" + stat + ": 重复登录:" + t);
            } else if (stat == 236) {//重复登录
                LogUtil.e(Constant.TAG, "stat =" + stat + ": 您的账户被举报封禁:" + t);
            } else {
                String message = jsonObject.getString("message");
                LogUtil.e(Constant.TAG, "onSuccess message = " + message);
                onError(stat, message);
            }
        } catch (Exception e) {
            LogUtil.e(Constant.TAG, "onSuccess exception = " + e.getMessage());
            onError(-101, "当前网络异常");
        }
    }

    @Override
    public void onFailure(int errorNo, String strMsg) {
        LogUtil.e(Constant.TAG, "onFailure errorNo = " + errorNo + " : strMsg = " + strMsg);
        super.onFailure(errorNo, strMsg);
        if (errorNo == -101 || errorNo == -1 || errorNo == 500) {
            strMsg = "当前无网络";
        }
        onError(errorNo, strMsg);
    }

    public abstract void onStart();

    public abstract void onSuccess(M result);

    public abstract void onError(int errorNo, String strMsg);
}